import axios from "axios";
import { UniAdapter } from "uniapp-axios-adapter";
import { getOmitBy } from "@/utils/utils";
const excludeApi = ['/passwordLogin']
import { hideLoading } from "@/utils/loading";
import store from "@/store";
import errorCode from "@/utils/errorCode";
const request = axios.create({
    baseURL: '/zgrsqfw-web',
    timeout: 10000,
    adapter: UniAdapter
});
// 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = []
request.interceptors.request.use((config) => {

    if (config.data) {
        if (config.data instanceof FormData) {
            config.headers['Content-Type'] = 'multipart/form-data'
        } else {
            config.data = {
                ...getOmitBy(config.data),
                villageId: store.state.userInfo.villageId
            }
        }

    }
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    if (!excludeApi.includes(config.url) && !isToken) {
        const water_token = uni.getStorageSync('water_token');
        //带上token
        config.headers["Authorization"] = `Bearer ${water_token}`;
    }
    return config;
});

request.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.status;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    // 二进制数据则直接返回
    if (res.request && (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer')) {
        return res.data
    }
    if (code === 401) {
        hideLoading()
        const config = res.config
        let pages = getCurrentPages()
        let url;
        if (pages.length) {
            let sUrl = pages.pop().route
            if (sUrl.startsWith('/pages')) {
                url = sUrl
            } else {
                url = `/${sUrl}`
            }
        }
        store.dispatch("delToken")
    } else if (code === 500) {
        hideLoading()
        uni.showModal({
            title: "提示",
            content: msg,
            showCancel: false
        })
        return Promise.reject(new Error(msg))
    } else if (code === 601) {
        uni.showModal({
            title: "提示",
            content: msg,
            showCancel: false
        })
        return Promise.reject('error')
    } else if (code !== 200) {
        uni.showModal({
            title: "提示",
            content: msg,
            showCancel: false
        })
        return Promise.reject('error')
    } else {
        if (res.data.code !== '0' && typeof res.data === 'object' && !Array.isArray(res.data)) {
            if (res.data.msg.startsWith('您已签到')) {
                return Promise.reject(res.data.msg)
            }
            uni.showToast({
                title: res.data.msg,
                content: "",
                icon: "none"
            })
            return Promise.reject(res.data.msg)
        }
        return res.data
    }
},
    error => {
        console.log('err' + error)
        let { message } = error;
        if (message === "Network Error") {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        uni.showModal({
            title: "提示",
            content: message,
            showCancel: false
        })
        return Promise.reject(error)
    }
)


// 进入获取用户信息
const getUser = (phone) => {
    return request({
        url: `/tbUser/getUser?phone=${phone}`,
        method: 'get'
    })
}

const login = async (phone, gis) => {
    // alert(phone + "@" + gis)
    let gisObj = {}
    if (gis) {
        gisObj.lng = gis.split(",")[0]
        gisObj.lat = gis.split(",")[1]
    }
    if (phone) {
        let res = await getUser(phone)
        //   alert(JSON.stringify(res))
        if (res && res.data) {
            res.data.villageId = 2
            store.dispatch("setUserInfo", { ...res.data, gisObj: gisObj })
            uni.setStorageSync('userInfo', res.data);
        } else {
            uni.setStorageSync('userInfo', {});
            uni.showModal({
                title: '提示',
                showCancel: false,
                content: res.msg || '未查询到用户信息',
            })
        }
    }
}
// 获取url的查询参数
const getQueryString = (name) => {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}
login(getQueryString('phone'), getQueryString('gis'))

export default request;
